
#include <gio/gio.h>
#include <string.h>
gchar *data = NULL;
static void
read_read_write_async_cb (GInputStream *istream,
                          GAsyncResult *result,
                          gpointer      user_data)
{
  GError *error = NULL;
  gboolean res;
  gsize bytes_read;
  GSocketConnection *conn;

  res = g_input_stream_read_all_finish (istream, result, &bytes_read, &error);
  g_debug ("L%d f-%s read:%d", __LINE__, __func__, bytes_read);
  g_assert_no_error (error);
  g_assert_true (res);

  g_input_stream_read_all_async (istream,
                                 data,
                                 20,
                                 G_PRIORITY_DEFAULT,
                                 NULL,
                                 (GAsyncReadyCallback) read_read_write_async_cb,
                                 data /* stolen */);

}

static void
incoming_read_write_async_cb (GSocketService    *service,
                              GSocketConnection *conn,
                              GObject           *source_object,
                              gpointer           user_data)
{
  GSocketConnection **cconn = user_data;
  GInputStream *istream;

  g_debug ("L%d f-%s", __LINE__, __func__);
  istream = g_io_stream_get_input_stream (G_IO_STREAM (conn));

  data = g_new0 (guint8, 20);

  g_object_ref (conn);
  g_input_stream_read_all_async (istream,
                                 data,
                                 20,
                                 G_PRIORITY_DEFAULT,
                                 NULL,
                                 (GAsyncReadyCallback) read_read_write_async_cb,
                                 data);

  *cconn = g_object_ref (conn);
}

int main(int argc, char **argv)
{
  g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);
  GSocketService *service;
  GError *error = NULL;
  GSocketClient *client;
  gint port = 14333;
  GSocketConnection *sconn = NULL;

  service = g_socket_service_new ();

  g_socket_listener_add_inet_port (G_SOCKET_LISTENER (service), port, NULL, &error);
  g_assert_no_error (error);

  g_signal_connect (service, "incoming", G_CALLBACK (incoming_read_write_async_cb), &sconn);

  g_socket_service_start (service);
  g_assert_true (g_socket_service_is_active (service));

  do
    {
      g_main_context_iteration (NULL, TRUE);
    }
  while (!sconn ||
         !g_io_stream_is_closed (G_IO_STREAM (sconn))
         );

  g_assert_true (GPOINTER_TO_INT (g_object_get_data (G_OBJECT (sconn), "test-data-read")));

  g_object_unref (sconn);
  g_object_unref (service);

}
